package com.watson.todolist;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.watson.todolist.constants.DatabaseConstants;
import com.watson.todolist.database.DatabaseManager;
import com.watson.todolist.database.ToDoListManager;
import com.watson.todolist.to.TodoItem;
import com.watson.todolist.to.TodoListAccount;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * This class handles searching the todo list and filtering items
 * 
 * @author Donnie Ward
 * 
 * @since 1.0
 * 
 */
public class SearchTodoList extends ListActivity {

	private long currentRowId;
	private ImageView currentCheckBox;
	private static String TAG = "SearchTodoList Class";

	private int categoryId = 0;
	private boolean completeDisplayed = true;
	private long date = 0;
	private long max;	//last occuring date in todo list
	private long min;	//first occuring date in todo list
	private int sliderMax;

	private Button completeButton; // complete/incomplete toggle button
	private Spinner categorySelect;
	private SeekBar dateSlider;

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.search_todo_list);

		populateTodoList();
		
		DatabaseManager dbManager = new DatabaseManager();
		SQLiteDatabase db = dbManager.open(getApplicationContext());
		ToDoListManager todoListManager = new ToDoListManager(db);
		todoListManager.getLastDateByUserId(TodoListAccount.getUserId());
		max = todoListManager.getLastDateByUserId(TodoListAccount.getUserId());
		min = todoListManager.getFirstDateByUserId(TodoListAccount.getUserId());
		sliderMax = (int) (max-min);
		dbManager.close();

		Button menuButtonMain = (Button) findViewById(R.id.menuButtonMain);
		Button menuButtonAdd = (Button) findViewById(R.id.menuButtonAdd);
		Button menuButtonSearch = (Button) findViewById(R.id.menuButtonSearch);
		Button menuButtonSettings = (Button) findViewById(R.id.menuButtonSettings);
		dateSlider = (SeekBar) findViewById(R.id.dateSlider);
		dateSlider.setMax(sliderMax);
		dateSlider.setKeyProgressIncrement(sliderMax/25);

		// change background image of search menu button (current screen)
		menuButtonSearch.setBackgroundResource(R.drawable.menu_search_);

		// Set up main menu button listener
		menuButtonMain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						todoListActivity.class);
				startActivity(intent);
			}
		});

		// Set up add todo button listener
		menuButtonAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(), AddTodoItem.class);
				startActivity(intent);
			}
		});

		// Set up settings button listener
		menuButtonSettings.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						SettingsPageActivity.class);
				startActivity(intent);
			}
		});

		// Spinner stuff - selects/listens to the category of the search

		categorySelect = (Spinner) findViewById(R.id.selectCategory);
		categorySelect.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				categoryId = arg2;
				populateTodoList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// do nothing
				populateTodoList();
			}
		});
		// end category spinner stuff

		// Completed button stuff - listens to when the completed/incomplete
		completeButton = (Button) findViewById(R.id.displayCompleteButton);
		completeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// change button text
				if (completeDisplayed) {
					completeButton.setText("Incomplete Only");
					completeDisplayed = false;
				} else {
					completeButton.setText("Complete and Incomplete");
					completeDisplayed = true;
				}
				populateTodoList();
			}
		});

		// end of Completed Button stuff
		
		// Date Slider stuff
				dateSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						date = (long) ((long)progress) + min;
						long currentProgress = progress + min;
						TextView text = (TextView) findViewById(R.id.descriptionOfSeekBar);
						text.setText("Displaying: " + currentProgress + " - " + max);
						populateTodoList();
						
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub
						
					}
				});

				// end of Date Slider stuff
	}

	/**
	 * This method populates the display of all to do list items on the screen
	 * 
	 */
	private void populateTodoList() {
				 
		DatabaseManager dbManager = new DatabaseManager();
		SQLiteDatabase db = dbManager.open(getApplicationContext());
		ToDoListManager todoListManager = new ToDoListManager(db);
		
		Cursor cursor;
		if (completeDisplayed) {
			cursor = todoListManager
					.getAllMatchesWithOutCompletedCriteriaIncluded(
							TodoListAccount.getUserId(),
							categoryId, date);
		}
		else{
			cursor = todoListManager
					.getAllMatchesWithCompletedCriteriaIncluded(
							TodoListAccount.getUserId(), 0,
							categoryId, date);
		}
		
		final ListView listView = this.getListView();
		
		final Spinner todoOptions = (Spinner) findViewById(R.id.invisibleSpinner);
		todoOptions.setOnItemSelectedListener(new todoOptionsListener());

		if (cursor != null) {
			startManagingCursor(cursor);
		}

		TextView displayMessage = (TextView) findViewById(R.id.todoListDisplayMessage);
		if (cursor == null || cursor.getCount() == 0) {
			displayMessage.setText("You currently have no Todo Items");
		} else {
			displayMessage.setText("");
			//populate list view
			String[] tableColumnNames = new String[] {
					DatabaseConstants.TODO_ITEM_TABLE_TODO_ITEM_NAME,
					DatabaseConstants.TODO_ITEM_TABLE_TODO_TIME };
			int[] textViewLabelNames = new int[] { R.id.todoTitle,
					R.id.todoDate };

			SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
					R.layout.todo_item_row, cursor, tableColumnNames,
					textViewLabelNames);
			this.setListAdapter(notes);
			
		}

		listView.setOnItemClickListener(new OnItemClickListener() {
			
			//Occurs when a ListView item is clicked.
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			
				currentRowId = id;
				currentCheckBox = (ImageView) ((RelativeLayout)view).getChildAt(0);
				
				//set selection back to zero after each selection necessary to function properly
				todoOptions.setSelection(0,true);
				todoOptions.performClick();
		}
		});
		dbManager.close();

	}

	/**
	 * This method gets called when one of the checkboxes to the left of a todo
	 * item is clicked, and toggles the displayed image to either checked or
	 * unchecked.
	 * 
	 * @param The
	 *            view clicked
	 */
	public void checkBoxHandler(View v) {

		// get the row the clicked button is in
		RelativeLayout clickedRow = (RelativeLayout) v.getParent();

		// gets the checkBox button of the clicked todo (item 0 in its relative
		// layout)
		Button checkBox = (Button) clickedRow.getChildAt(0);

		// View checkedImg = (View) findViewById(R.drawable.checked);
		// View uncheckedImg = (View) findViewById(R.drawable.unchecked);

		// toggles the image by looking at the String tag of the image in the
		// XML file
		// this could be changed to look to the db instead of the XML tag (but I
		// needed a way to test that the toggling worked)

		ListView listView = (ListView) findViewById(android.R.id.list);
		long id = listView.getPositionForView(v) + 1;

		DatabaseManager dbManager = new DatabaseManager();
		SQLiteDatabase db = dbManager.open(getApplicationContext());
		ToDoListManager todoListManager = new ToDoListManager(db);
		TodoItem todoItem = todoListManager.getTodoListItemByTodoId(id);

		if (((String) checkBox.getTag()).equals("checked")) {
			checkBox.setBackgroundResource(R.drawable.unchecked);
			checkBox.setTag("unchecked");

			todoListManager.updateTodoListItemByTodoItemId(id,
					TodoListAccount.getUserId(), todoItem.getTodoItemName(),
					todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
					todoItem.getLatitude(), todoItem.getLongitude(),
					todoItem.getDescription(),
					todoItem.getAlarmRecurrenceType(),
					todoItem.getPriorAlarmReminderTime(), 0);

		} else {
			checkBox.setBackgroundResource(R.drawable.checked);
			checkBox.setTag("checked");

			todoListManager.updateTodoListItemByTodoItemId(id,
					TodoListAccount.getUserId(), todoItem.getTodoItemName(),
					todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
					todoItem.getLatitude(), todoItem.getLongitude(),
					todoItem.getDescription(),
					todoItem.getAlarmRecurrenceType(),
					todoItem.getPriorAlarmReminderTime(), 1);

		}

		// close database
		dbManager.close();

		// must refresh view to display new image
		clickedRow.refreshDrawableState();

	}

	/**
	 * Responsible for responding when the user selects a value in the spinner that appears
	 * when a todo item is clicked 
	 * 
	 * @param The clicked view
	 */
	private class todoOptionsListener implements OnItemSelectedListener {
		

		@Override
		public void onNothingSelected(AdapterView<?> parent) {
			// do nothing
			
		}

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			
			DatabaseManager dbManager = new DatabaseManager();
			SQLiteDatabase db = dbManager.open(getApplicationContext());
			ToDoListManager todoListManager = new ToDoListManager(db);
			TodoItem todoItem = todoListManager.getTodoListItemByTodoId(currentRowId);
			
			switch (pos) {
			//do nothing ("back" selected)
			//this is necessary b/c option 0 is automatically called when spinner created 
			case 0:
				break;
				
			//change state of check mark
			case 1:
				//if todo item is unchecked
				//TODO what about having some sort of image to allow the user to know the item has been checked or a custom toast or just setting the background of the button
				// to red for unchecked and green for checked... whatever works :P
				if(todoItem.getTodoCompleted()==0) {
					todoItem.setTodoCompleted(1);
					//update the database
					todoListManager.updateTodoListItemByTodoItemId(todoItem.getTodoItemId(),
							todoItem.getUserId(),todoItem.getTodoItemName(),
							todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
							todoItem.getLatitude(), todoItem.getLongitude(),
							todoItem.getDescription(), todoItem.getAlarmRecurrenceType(),
							todoItem.getPriorAlarmReminderTime(), 1);
					currentCheckBox.setImageResource(R.drawable.checked);
					Toast toast = Toast.makeText(getApplicationContext(), "Item set to Completed", Toast.LENGTH_SHORT);
					toast.show();
				}
				// if todo item is checked
				else {
					todoItem.setTodoCompleted(0);
					//update the database
					todoListManager.updateTodoListItemByTodoItemId(todoItem.getTodoItemId(),
							todoItem.getUserId(),todoItem.getTodoItemName(),
							todoItem.getTodoItemCategoryCode(), todoItem.getTodoTime(),
							todoItem.getLatitude(), todoItem.getLongitude(),
							todoItem.getDescription(), todoItem.getAlarmRecurrenceType(),
							todoItem.getPriorAlarmReminderTime(), 0);
					currentCheckBox.setImageResource(R.drawable.unchecked);
					Toast toast = Toast.makeText(getApplicationContext(), "Item set to Uncompleted", Toast.LENGTH_SHORT);
					toast.show();
				}
				break;
			
			// View Activity
			case 2:
				dbManager.close();
				Intent viewIntent = new Intent(view.getContext(), ViewTodoItemActivity.class);
				viewIntent.putExtra("ToDoItemLongId", currentRowId);
				startActivity(viewIntent);
				break;
			
			//Edit Activity
			case 3:
				dbManager.close();
				Intent editIntent = new Intent(view.getContext(), EditTodoItemActivity.class);
				editIntent.putExtra("ToDoItemLongId", currentRowId);
				startActivity(editIntent);
				break;
			
			//Delete
			case 4:
				todoListManager.deleteTodoListItemById(todoItem.getTodoItemId());
				break;	
			}
			
			dbManager.close();
			populateTodoList();
			
		}
	}

}
